import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:opene/JhPickerTool.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/checkin/checkin.dart';
import 'package:opene/utils/ImageUtils.dart';
import 'package:toast/toast.dart';

import '../../app_constant.dart';
import 'checkinmodel.dart';

class CheckinVerify extends StatelessWidget {
  CheckinInfo data;
  CheckinPendingModel checkinPending;

  CheckinVerify({this.data, this.checkinPending});

  @override
  Widget build(BuildContext context) {
    return CheckinVerifyPage(checkinInfo: data, checkinPending: checkinPending);
  }
}

class CheckinVerifyPage extends StatefulWidget {
  CheckinInfo checkinInfo;
  CheckinPendingModel checkinPending;

  CheckinVerifyPage({this.checkinInfo, this.checkinPending});

  @override
  _CheckinVerifyPageState createState() => _CheckinVerifyPageState(checkinInfo: checkinInfo, checkinPending: checkinPending);
}

class _CheckinVerifyPageState extends BaseState<CheckinVerifyPage> {
  CheckinInfo checkinInfo;
  CheckinPendingModel checkinPending;

  _CheckinVerifyPageState({this.checkinInfo, this.checkinPending});

  final TextEditingController dateController = TextEditingController();
  final TextEditingController productController = TextEditingController();
  final controller = ScrollController();
  String containerNo, uniqId, tvspecialrequest, tvPhoto, tvContainerNoHint = "Container NO#: ";
  List<PhotoBean> bolPhotos = new List();

  bool layoutCartonsQty = false, layoutQty = false, layoutProductQty = false, layoutSpecialRequest = true, tvPhotoHint = true, layoutContent = true;

  int index = 0, position;

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Checkin:Submit";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      next = "Submit";
      containerNo = checkinInfo.containerNo;
      uniqId = checkinInfo.uniqId;
      bolPhotos.add(new PhotoBean());
      if (checkinPending.isPallet) {
        layoutQty = true;
      } else {
        layoutQty = false;
      }

      if (checkinPending.isSpecialRequest) {
        layoutSpecialRequest = true;
      } else {
        layoutSpecialRequest = false;
      }

      layoutCartonsQty = false;
      if (checkinInfo.operationMethod == "truck") {
        layoutCartonsQty = true;
        this.type = 2;
        tvContainerNoHint = "BOL NO#: ";
        tvPhoto = "BOL: ";

        List<String> damagedList = checkinInfo.bol;
        if (damagedList != null && damagedList.length > 0) {
          damagedList.forEach((value) {
            PhotoBean photoBean = new PhotoBean();
            photoBean.urlImg = value;
            bolPhotos.add(photoBean);
          });
        }
        layoutSpecialRequest = false;
      } else if (checkinInfo.operationMethod == "express") {
        this.type = 3;
        layoutCartonsQty = true;
        if (checkinPending.isVerifiedQty) {
          layoutProductQty = true;
        } else {
          layoutProductQty = false;
        }
        tvContainerNoHint = "Tracking NO#: ";
        tvPhotoHint = false;
        tvPhoto = "Special Request Photo: ";
        if (!checkinPending.isSpecialRequest) {
          layoutSpecialRequest = false;
          layoutContent = false;
        }
        tvspecialrequest = Utils.getStringisEmpty(checkinPending.specialRequest);

        List<String> damagedList = checkinInfo.specialRequest;
        if (damagedList != null && damagedList.length > 0) {
          damagedList.forEach((value) {
            PhotoBean photoBean = new PhotoBean();
            photoBean.urlImg = value;
            bolPhotos.add(photoBean);
          });
        }
      }
    });
  }

  Future pickImages(context) async {
    File image = await ImageUtils.chosePhotoOnAlbumOrCamera(context: context);
    print(image.path);
    String name = "";
    setState(() {
      PhotoBean photoBean = new PhotoBean();
      photoBean.image = image;
      bolPhotos.insert(position, photoBean);
      name = "bol";

      fileUpload(containerNo, "checkin", image, name, index, position, false, false);
      print("index:${index},position:${position}");
      print(image.path);
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 0, top: 10, right: 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only(left: 15),
            child: Row(
              children: [
                Text(
                  "Container NO#: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Text(
                  Utils.getStringisEmpty(containerNo),
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15),
            child: Row(
              children: [
                Text(
                  "Uniq ID: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Text(
                  Utils.getStringisEmpty(uniqId),
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ],
            ),
          ),
          Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 1,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: null,
                      ),
                    ),
                    Text(
                      'Container',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: this.type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 12.0),
                    ),
                  ],
                ),
              ),
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 2,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: null,
                      ),
                    ),
                    Text(
                      'Truck',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: this.type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 12.0),
                    ),
                  ],
                ),
              ),
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 3,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: null,
                      ),
                    ),
                    Text(
                      'Package',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: this.type == 3 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 12.0),
                    ),
                  ],
                ),
              ),
            ],
          ),
          Visibility(
            visible: layoutQty,
            child: Container(
              margin: const EdgeInsets.only(left: 15, top: 5, right: 15, bottom: 0),
              width: double.infinity,
              child: Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: ConstrainedBox(
                      constraints: BoxConstraints(maxHeight: 40),
                      child: TextField(
                        controller: textEditingController,
                        textInputAction: TextInputAction.search,
                        onSubmitted: (String text) {
                          print('Searching for $text');
                        },
                        // autofocus: true,
                        decoration: InputDecoration(
                          border: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: MyAppTheme.nearlyBlue,
                            ),
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点之外的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点时的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          hintText: "please scan the dock num",
                          filled: true,
                          fillColor: MyAppTheme.white,
                          //隐藏下划线
                          //border: InputBorder.none,
                          hintStyle: TextStyle(color: Colors.grey),
                          contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                        ),
                      ),
                    ),
                  ),
                  Text(
                    "  Pallets QTY",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                ],
              ),
            ),
          ),
          Visibility(
            visible: layoutCartonsQty,
            child: Container(
              margin: const EdgeInsets.only(left: 15, top: 5, right: 15, bottom: 0),
              width: double.infinity,
              child: Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: ConstrainedBox(
                      constraints: BoxConstraints(maxHeight: 40),
                      child: TextField(

                        controller: dateController,
                        textInputAction: TextInputAction.search,
                        onSubmitted: (String text) {
                          print('Searching for $text');
                        },
                        // autofocus: true,
                        decoration: InputDecoration(
                          border: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: MyAppTheme.nearlyBlue,
                            ),
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点之外的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点时的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          hintText: "qty of checkin pallets",
                          filled: true,
                          fillColor: MyAppTheme.white,
                          //隐藏下划线
                          //border: InputBorder.none,
                          hintStyle: TextStyle(color: Colors.grey),
                          contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                        ),
                      ),
                    ),
                  ),
                  Text(
                    "Carton QTY",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                ],
              ),
            ),
          ),
          Visibility(
            visible: layoutProductQty,
            child: Container(
              margin: const EdgeInsets.only(left: 15, top: 5, right: 15, bottom: 0),
              width: double.infinity,
              child: Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: ConstrainedBox(
                      constraints: BoxConstraints(maxHeight: 40),
                      child: TextField(
                        controller: productController,
                        textInputAction: TextInputAction.search,
                        onSubmitted: (String text) {
                          print('Searching for $text');
                        },
                        // autofocus: true,
                        decoration: InputDecoration(
                          border: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: MyAppTheme.nearlyBlue,
                            ),
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点之外的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点时的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          hintText: "qty of checkin products",
                          filled: true,
                          fillColor: MyAppTheme.white,
                          //隐藏下划线
                          //border: InputBorder.none,
                          hintStyle: TextStyle(color: Colors.grey),
                          contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                        ),
                      ),
                    ),
                  ),
                  Text(
                    "Product QTY",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                ],
              ),
            ),
          ),
          Visibility(
            visible: layoutSpecialRequest,
            child: Container(
              margin: const EdgeInsets.only(left: 15, top: 10, right: 15, bottom: 0),
              width: double.infinity,
              child: Column(
                children: [
                  Text(
                    "Special Request: ",
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                  Text(
                    Utils.getStringisEmpty(tvspecialrequest),
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                  ),
                ],
              ),
            ),
          ),
          Visibility(
            visible: layoutContent,
            child: Container(
              margin: EdgeInsets.only(left: 15,top: 10),
              child: Column(
                children: [
                  Visibility(
                    visible: tvPhotoHint,
                    child: Text(
                      '*',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
                    ),
                  ),
                  Text(
                    Utils.getStringisEmpty(tvPhoto),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                  ),
                ],
              ),
            ),
          ),
          Visibility(
            visible: layoutContent,
            child:   Expanded(
              child: Container(
                margin: EdgeInsets.only(left: 15),
                child: setListView(8, bolPhotos),
              ),
            ),
          ),

        ],
      ),
    );
  }

  ListView setListView(int type, List<PhotoBean> data) {
    return ListView.builder(
      scrollDirection: Axis.horizontal,
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        PhotoBean photoBean = data[index];
        print(photoBean.toString());
        return Container(
          height: 70,
          width: 70,
          margin: const EdgeInsets.only(left: 0, top: 0, right: 10, bottom: 0),
          child: Stack(
            children: <Widget>[
              GestureDetector(
                onTap: () {
                  // 请求焦点
                  FocusScope.of(context).requestFocus(FocusNode());
                  this.index = type;
                  this.position = index;
                  photoBean.image == null ? pickImages(context) : imgFileDialog(photoBean, Constants.baseImgUrl);
                },
                child: photoBean.image == null
                    ? Image.asset(
                        'assets/images/add.png',
                        width: 70,
                        height: 70,
                        fit: BoxFit.cover,
                      )
                    : Image.file(
                        photoBean.image,
                        width: 70,
                        height: 70,
                        fit: BoxFit.cover,
                      ),
              ),
              Visibility(
                visible: photoBean.image == null ? false : true,
                child: Positioned(
                  top: 2.0,
                  left: 53,
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        data.removeAt(index);
                      });
                    },
                    child: Image.asset(
                      'assets/images/ic_delete_menu.png',
                      width: 15,
                      height: 15,
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    bolPhotos[position].urlImg = path;

    if (isSubmit) {
      submitData();
    }
  }

  @override
  void setNext() {
    submitData();
  }

  void submitData() {
    ToastContext().init(context);

    CheckinVerifyQr checkinVerify = new CheckinVerifyQr();
    checkinVerify.id = checkinInfo.id;
    String palletQty = textEditingController.text;
    if (checkinPending.isPallet) {
      if (Utils.isEmpty(palletQty) || (int.parse(palletQty) == 0)) {
        Toast.show("Please enter the number of pallets", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      checkinVerify.palletsQty=int.parse(palletQty);
    }

    if (layoutCartonsQty) {
      String cartonsQty = dateController.text;
      if (Utils.isEmpty(cartonsQty) || (int.parse(cartonsQty) == 0)) {
        Toast.show("Please enter the number of cartons", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      checkinVerify.cartonsQty=int.parse(cartonsQty);
    }

    if (layoutProductQty) {
      String productQty = productController.text;
      if (Utils.isEmpty(productQty) || (int.parse(productQty) == 0)) {
        Toast.show("Please enter the number of products", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      checkinVerify.productQty=int.parse(productQty);
    }

    if (checkinInfo.operationMethod=="truck") {
      if (bolPhotos.length <2) {
        Toast.show("Please add bol photos", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }

      List<String> tamp = new List();
      for (int i = 0; i < bolPhotos.length - 1; i++) {
        PhotoBean photoBean = bolPhotos[i];

        if (Utils.isEmpty(photoBean.urlImg)) {
          position = i;
          fileUpload(containerNo, "checkin", photoBean.image, "bol", 7, position, true, true);
        }else{
          tamp.add(photoBean.urlImg);
        }
      }
      checkinVerify.bol= tamp;
    } else if (checkinInfo.operationMethod=="express") {
      if (checkinPending.isSpecialRequest) {
        if (bolPhotos.length <2) {
          Toast.show("Please add special request photos", duration: Toast.lengthShort, gravity: Toast.bottom);
          return;
        }
      }


      List<String> tamp = new List();
      for (int i = 0; i < bolPhotos.length - 1; i++) {
        PhotoBean photoBean = bolPhotos[i];

        if (Utils.isEmpty(photoBean.urlImg)) {
          position = i;
          fileUpload(containerNo, "checkin", photoBean.image, "special_request", 7, position, true, true);
        }else{
          tamp.add(photoBean.urlImg);
        }
      }
      checkinVerify.specialRequestPhoto=tamp;
    }

    checkSubmit(checkinVerify);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      dateController.text = "";
      productController.text = "";
      bolPhotos.clear();
      bolPhotos.add(new PhotoBean());
    });
  }

  void checkSubmit(CheckinVerifyQr checkinVerify) async {
    String json = jsonEncode(checkinVerify);
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.checkSubmit, method: BaseMethod.put, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
        Navigator.pop(context, true);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
}
